package elements;

import java.awt.Graphics;
import java.awt.Polygon;

import scaler.Scaler;

import mover.GameMover;

public class GamePolygon extends GameElement {
	private Polygon pol;
	private int heigth = Integer.MIN_VALUE, width = Integer.MIN_VALUE;
	
	public GamePolygon(int[] xpoints, int[] ypoints, int npoints, GameMover mover, Scaler scaler) {
		super(mover, scaler);
		this.pol = new Polygon(xpoints, ypoints, npoints);
	}
	
	public GamePolygon(Polygon p, GameMover mover, Scaler scaler) {
		super(mover, scaler);
		this.setPolygon(p);
	}
	
	public GamePolygon() {
		super(NO_MOVEMENT, Scaler.NO_SCALING);
		pol = new Polygon();
	}
	
//	@Override
//	/**
//	 * Resets the polygon
//	 */
//	public void reset() {
//		super.reset();
//		this.pol = new Polygon(); 
//	}
	
	@Override
	public void paint(Graphics g) {
		if(trans == NOT_VISIBLE) return;
		
		int[] xTmp = pol.xpoints.clone(), yTmp = pol.ypoints.clone();
		for(int i = 0; i<pol.npoints; i++) {
			xTmp[i] = scaler.calcX(xTmp[i]) + this.getMovedX();
			yTmp[i] = scaler.calcY(yTmp[i]) + this.getMovedY();
		}
		
		g.setColor(transparentColor());
		g.fillPolygon(xTmp, yTmp, pol.npoints);
	}
	
	private void setPolygon(Polygon p) {
		// Copys the given polygon
		this.pol = new Polygon(p.xpoints.clone(),
				p.ypoints.clone(),
				p.npoints);
		
		width = heigth = Integer.MIN_VALUE;
	}

	@Override
	public int getWidth() {
		if(width != Integer.MIN_VALUE) return width;
		
		int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE;
		int xVal[] = pol.xpoints;
		
		for(int i = 0; i<xVal.length; i++) {
			if(xVal[i] < minX) minX = xVal[i];
			if(xVal[i] > maxX) maxX = xVal[i];
		}
		width = maxX - minX;
		
		return width;
	}

	@Override
	public int getHeight() {
		if(heigth != Integer.MIN_VALUE) return heigth;
		
		int minY = Integer.MAX_VALUE, maxY = Integer.MIN_VALUE;
		int YVal[] = pol.ypoints;
		
		for(int i = 0; i<YVal.length; i++) {
			if(YVal[i] < minY) minY = YVal[i];
			if(YVal[i] > maxY) maxY = YVal[i];
		}
		heigth = maxY - minY;
		
		return heigth;
	}

	@Override
	public GamePolygon clone() throws CloneNotSupportedException {
		GamePolygon clone = new GamePolygon(new Polygon(this.pol.xpoints.clone(), this.pol.ypoints.clone(), this.pol.npoints), this.mover.clone(), this.scaler);
		this.clone_help(clone);
		clone.heigth = this.heigth;
		clone.width = this.width;
		
		return clone;
	}
}
